import React, {useContext, useState } from 'react';
import StuContext from '../store/StuContext';
import StudentForm from './StudentForm';
import useFetch from '../hooks/useFetch';

const Student = ({stu:{documentId,name, age, gender, address}}) => {
    // const [loading, setLoading] = useState(false);
    // const [error, setError] = useState(null);
    const [isEdit, setIsEdit] = useState(false);
    const ctx = useContext(StuContext)

    console.log(documentId);
    const {loading, error, fetchData:delStu} = useFetch({
        url:`students/${documentId}`,
        method:'delete'
    },ctx.fetchData)
    const deleteHandler = () => {
        delStu()
    }
    const cancelEdit = () => {
        setIsEdit(false)
    }

    return (
            <>
            {!isEdit &&
                <tr>
                    <td>{name}</td>
                    <td>{gender}</td>
                    <td>{age}</td>
                    <td>{address}</td>
                    <td>
                        <button onClick={deleteHandler}>删 除</button>
                        <button onClick={()=>{setIsEdit(true)}}>修 改</button>
                    </td>
                </tr>
            }
            {isEdit && <StudentForm
                isEdit={isEdit}
                stu={{documentId, name, age, gender, address}}
                onCancel={cancelEdit}
            ></StudentForm>}

            {loading && <tr><td colSpan={5}>正在删除数据</td></tr>}
            {error && <tr><td colSpan={5}>删除失败</td></tr>}
            </>
    );
};

export default Student;
